/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Classes;

import AuxClasses.MD5;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;

/**
 *
 * @author Marvin
 */
public class Login extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HttpSession actual = request.getSession();
        String correo = request.getParameter("correo");
        String contrasena = request.getParameter("contrasena");
        
        Connection conn = null;
        Statement s = null;
        ResultSet rs = null;
        String userName = "root";
        String password = "1234";
        String url = "jdbc:mysql://localhost/bancofarmville";
        try
        {
            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
            conn = DriverManager.getConnection (url, userName, password);
            System.out.println ("Database connection established");
            s = conn.createStatement ();

            if (correo.equals("") || contrasena.equals(""))
            {
                String error = "";
                if (correo.equals(""))
                {
                    error= "<p style=\"color:red\">(*) Error: Debe introducir un correo electronico</p>";
                }
                if (contrasena.equals(""))
                {
                    error=error+"<p style=\"color:red\">(*) Error: Debe introducir un contraseña</p>";
                }
                actual.setAttribute("error_correo", error);
                response.sendRedirect("login.jsp");
            }
            else
            {
                s.executeQuery ("SELECT * FROM usuario WHERE correo_electronico=\""+correo+"\"");
                rs = s.getResultSet ();
                if (rs.next())
                {
                    System.out.println ();
                    MD5 md5 = new MD5();
                    String hash = md5.getMD5(contrasena);
                    if (hash.equalsIgnoreCase(rs.getString("password")))
                    {
                        actual.setAttribute("error_correo", null);
                        actual.setAttribute("user", rs.getString("nombre")+" "+rs.getString("apellido"));
                        actual.setAttribute("correo",correo);
                        actual.setAttribute("dpi", rs.getString("dpi"));
                        response.sendRedirect("index.jsp");
                    }
                    else
                    {
                        actual.setAttribute("error_correo", "<p style=\"color:red\">(*) Error: Contraseña Incorrecta</p>");
                        response.sendRedirect("login.jsp");
                    }
                }
                else
                {
                    actual.setAttribute("error_correo", "<p style=\"color:red\">(*) Error: No se encontro usuario</p>");
                    response.sendRedirect("login.jsp");
                }
            }
           
        }
        catch (Exception e)
        {
           System.err.println ("No se pudo conectar a la base de datos " + e.getMessage());
        }
        finally
        {
           if (conn != null)
           {
               try
               {
                   conn.close ();
                   System.out.println ("Conexión Finalizada");
               }
               catch (Exception e) {  }
           }
        }
        
        
        
        /*PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Login</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Login at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             
        } finally {            
            out.close();
        }*/
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
